package com.woniu.service;

import com.woniu.adapter.RiskRepositoryApater;
import com.woniu.adapter.UserRepositoryApater;
import com.woniu.exception.RiskException;
import com.woniu.exception.UserException;
import com.woniu.inlet.web.command.RiskCommand;
import com.woniu.inlet.web.command.RiskCommandHandle;
import com.woniu.outlet.mysql.po.Risk;
import com.woniu.outlet.mysql.po.RiskExample;
import com.woniu.service.domain.RiskDto;
import com.woniu.service.domain.UserDo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class RiskService implements RiskCommandHandle {

    @Autowired
    private RiskRepositoryApater riskRepositoryApater;

    @Autowired
    private UserRepositoryApater userRepositoryApater;

    //根据风险评测分数给出评测结果
    @Override
    public RiskDto action(RiskCommand command) {
        if (command.getScore() < 10 || command.getScore() > 50) {
            throw new RiskException("测评的分数有误！");
        }
        RiskExample example = new RiskExample();
        example.or().andLowestScoreLessThanOrEqualTo(command.getScore())
                .andHighestScoreGreaterThanOrEqualTo(command.getScore());

        List<Risk> risks = riskRepositoryApater.selectByExample(example);

        RiskDto riskDto = new RiskDto();
        BeanUtils.copyProperties(risks.get(0), riskDto);
        //根据用户id设置用户的风险评测结果
        UserDo userDo = userRepositoryApater.getById(command.getUserId());
        if (userDo.getRiskId() != null) {
            throw new RiskException("该用户已经测评过了");
        }
        userDo.setRiskId(riskDto.getId());

        userRepositoryApater.updateInfo(userDo);

        return riskDto;
    }

    //根据riskId查询
    public RiskDto getById(Integer riskId) {
        RiskDto riskDto = riskRepositoryApater.getById(riskId);
        return riskDto;
    }

}
